package com.ming.elm.service.impl;

import com.ming.elm.dao.UserDao;
import com.ming.elm.po.User;
import com.ming.elm.service.UserService;
import com.ming.elm.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

public class UserServiceImpl implements UserService{

	@Override
	public User getUserByIdByPass(String userId, String password) {
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		UserDao mapper = sqlSession.getMapper(UserDao.class);
		User user = null;
		try {
			user = mapper.getUserByIdByPass(userId, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(user!=null){
			user.setPassword("");
		}
		return user;
	}
	
	@Override
	public User getUserById(String userId) {
		User user = null;
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		UserDao mapper = sqlSession.getMapper(UserDao.class);

		try {
			user = mapper.getUserById(userId);
			System.out.println(user);
			if(user!=null){
				user.setPassword("");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}

		return user;
	}
	
	@Override
	public int saveUser(User user) {
		int result = 0;
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		UserDao mapper = sqlSession.getMapper(UserDao.class);

		try {
			result = mapper.saveUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		} finally {
			sqlSession.commit();
			sqlSession.close();
		}
		return result;
	}

	@Override
	public int updateUserImg(User user) {
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		UserDao mapper = sqlSession.getMapper(UserDao.class);
		int result = 0;
		try {
			result = mapper.updateUserImg(user);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		} finally {
			sqlSession.commit();
			sqlSession.close();
		}
		return result;
	}

	@Override
	public int updatePwd(User user) {
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		UserDao mapper = sqlSession.getMapper(UserDao.class);
		int result = 0;
		try {
			result = mapper.updatePwd(user);
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
		} finally {
			sqlSession.commit();
			sqlSession.close();
		}
		return result;
	}

	@Override
	public int isSameOldPwd(User user) {
		SqlSession sqlSession = MybatisUtil.getSqlSession();
		UserDao mapper = sqlSession.getMapper(UserDao.class);
		int result = 0;
		try {
			User oldUser = mapper.getUserById(user.getUserId());
			// 判断原密码与请求密码是否一致
			if(oldUser!=null){
				if(user.getPassword().equals(oldUser.getPassword())){
					result = 1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sqlSession.close();
		}

		return result;
	}
}
